package ee.ut.test.adapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang3.time.DateUtils;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import ee.ut.test.R;
import ee.ut.test.model.ScheduleTimeListItem;

public class ScheduleTimeListAdapter extends ArrayAdapter<ScheduleTimeListItem>{

	private List<ScheduleTimeListItem> items;
	private Context context;
	
	private Date previousDate;
	
	public ScheduleTimeListAdapter(Context context, List<ScheduleTimeListItem> items){
		super(context, R.layout.schedule_time_list_row, items);
		this.context = context;
		this.items = items;
	}
	
	static class ViewHolder {
		protected TextView formattedDate;
	}
	
	public boolean isEnabled(int position) {
	       return items.get(position).isSelectable();
	}

	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ScheduleTimeListItem item = items.get(position);

		View view = null;
		if (convertView == null) {
			LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = inflator.inflate(R.layout.schedule_time_list_row, null);
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.formattedDate = (TextView) view.findViewById(R.id.scheduleTimeListDate);
			if(previousDate != null && DateUtils.isSameDay(previousDate, item.getDate())){
				viewHolder.formattedDate.setPadding(10, 0, 0, 0);
			} else {
				viewHolder.formattedDate.setBackgroundColor(Color.parseColor("#5C5C5C"));
				viewHolder.formattedDate.setTextColor(Color.parseColor("#C0C0C0"));
			}
			view.setTag(viewHolder);
		} else {
			view = convertView;
		}

		ViewHolder holder = (ViewHolder) view.getTag();
		if(previousDate != null && DateUtils.isSameDay(previousDate, item.getDate())){
			holder.formattedDate.setText(getFormattedTime(item.getDate(), "HH:mm"));
		} else {
			holder.formattedDate.setText(getFormattedTime(item.getDate(), "EEEE, dd.MM.yyyy"));
			ScheduleTimeListItem copy = new ScheduleTimeListItem();
			copy.setDate(item.getDate());
			copy.setId(item.getId());
			item.setSelectable(false);
			items.add(items.indexOf(item) + 1, copy);
			notifyDataSetChanged();
		}
		previousDate = item.getDate();
		
		return view;
	}
	
	private String getFormattedTime(Date date, String pattern){
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
		return dateFormat.format(date);
	}
}
